#include "AnimationUnit.h"

using namespace cocos2d;

CAnimationUnit::CAnimationUnit(void)
	:m_pSprite(NULL)
	,m_pAnimation(NULL)
	,m_pAction(NULL)
	,m_group(0)
	,m_startFrame(0)
	,m_endFrame(0)
	,m_curFrame(0)
{
}


CAnimationUnit::~CAnimationUnit(void)
{
}

bool CAnimationUnit::Init( CResourceUnit* resource, int group, int startframe, int endframe )
{
	bool bRet = false;
	do 
	{
		CC_BREAK_IF(!resource);
		CC_BREAK_IF(group<0 || startframe<0 || endframe<startframe);

		m_pSprite = CCSprite::createWithSpriteFrameName("0_0.png");
		CC_BREAK_IF(!m_pSprite);

		resource->AddSprite(m_pSprite);

		m_pAnimation = CCAnimation::create();
		CC_BREAK_IF(!m_pAnimation);

		m_pAction = CCAnimate::create(m_pAnimation);
		CC_BREAK_IF(!m_pAction);

		for(int i = startframe; i < endframe+1; i++)
		{
			char str[32] = {0};
			sprintf(str,"%d_%d.png",group,i);
			m_pAnimation->addSpriteFrameWithFileName(str);
		}

		m_group = group;
		m_startFrame = startframe;
		m_endFrame = endframe;
		m_curFrame = m_startFrame;

		bRet = true;
	} while (0);

	return bRet;
}

void CAnimationUnit::SetLoops( int times )
{
	if(m_pAnimation)
		m_pAnimation->setLoops(times);
}

void CAnimationUnit::SetDelayPerUnit( float dt )
{
	if(m_pAnimation)
		m_pAnimation->setDelayPerUnit(dt);
}

void CAnimationUnit::SetRestoreOriginalFrame( bool b )
{
	if(m_pAnimation)
		m_pAnimation->setRestoreOriginalFrame(b);
}

void CAnimationUnit::Play()
{
	if(m_pAction && m_pSprite)
		m_pSprite->runAction(m_pAction);
}

void CAnimationUnit::Stop()
{
	if(m_pAction && m_pSprite)
		m_pSprite->stopAction(m_pAction);
}